package com.woniuxy.confirm;

import com.rabbitmq.client.Channel;
import com.woniuxy.commen.ConnUtils;
import com.woniuxy.commen.Constansts;

import java.io.IOException;

public class ConfirmConsumer {
    private String name;
    //(1) 加入bindingKey，用于队列与交换机的绑定
    private String bindingKey;

    public ConfirmConsumer(String name, String bindingKey) {
        this.name = name;
        this.bindingKey = bindingKey;
    }

    public void consume() throws IOException {
        //建立信道
        Channel channel = ConnUtils.getconn();

        //创建交换机

        //创建消息队列
        String queueName = channel.queueDeclare().getQueue();

        //（2）通过bindingkey来绑定交换机
        channel.queueBind(queueName, Constansts.ROUTE_EXCHANGE,bindingKey);

        //接收消息
        /**
         * queue  队列名
         * autoAck 自动确认收到
         * deliverCallback  收到消息处理
         * cancelCallback   取消消息处理
         */
        channel.basicConsume(queueName,true,
                (consumerTag,delivery)->{
                    //处理消息
                    byte[] body = delivery.getBody();
                    String message = new String(body,"utf-8");
                    System.out.println(name + "[x] 收到消息"+message);
                },(consumerTag)->{});
    }
}
